﻿using System;
using System.Collections.Generic;

namespace VkApi
{
    public class VkAuthResult
    {
        public VkAuthResult(string accessToken, DateTime expires, string userId)
        {
            AccessToken = new VkAccessToken(accessToken, expires);
            UserId = userId;
        }

        public VkAuthResult(IDictionary<string, string> parameters)
        {
            AccessToken = new VkAccessToken();

            if (parameters.ContainsKey("access_token"))
            {
                AccessToken.Token = parameters["access_token"];
            }

            if (parameters.ContainsKey("expires_in"))
            {
                var expiresIn = Convert.ToDouble(parameters["expires_in"]);
                AccessToken.Expires = expiresIn == 0 ? DateTime.MaxValue : DateTime.UtcNow.AddSeconds(expiresIn);
            }

            if (parameters.ContainsKey("error"))
            {
                Error = parameters["error"];
            }

            if (parameters.ContainsKey("error_description"))
            {
                ErrorDescription = parameters["error_description"];
            }

            if (parameters.ContainsKey("user_id"))
            {
                UserId = parameters["user_id"];
            }
        }



        public VkAccessToken AccessToken { get; private set; }

        public string UserId { get; set; }

        public string Error { get; private set; }

        public string ErrorDescription { get; private set; }

        public bool IsSuccess
        {
            get { return (string.IsNullOrEmpty(Error)); }
        }

        #region Static members

        public static VkAuthResult Parse(Uri uri)
        {
            return Parse(uri, true);
        }

        private static VkAuthResult Parse(Uri uri, bool throwExceptions)
        {
            try
            {
                if (!string.IsNullOrEmpty(uri.Fragment))
                {
                    var fragment = uri.Fragment.Substring(1); //get fragment without '#'
                    IDictionary<string, string> parameters = VkUtils.ParseFragment(fragment);
                    if (parameters.ContainsKey("access_token") || parameters.ContainsKey("error"))
                    {
                        return new VkAuthResult(parameters);
                    }
                }

                if (throwExceptions)
                {
                    throw new InvalidOperationException("Unable to parse url.");
                }

                return null;

            }
            catch (Exception ex)
            {
                //logger.Error("Unable to parse url. " + ex);
                return null;
            }
        }

        public static bool TryParse(string uriString, out VkAuthResult result)
        {
            if (Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute))
            {
                return TryParse(new Uri(uriString), out result);
            }

            result = null;
            return false;
        }

        public static bool TryParse(Uri uri, out VkAuthResult result)
        {
            result = Parse(uri, false);
            return result != null;
        }

        #endregion
    }
}
